package com.example.werewolf.service.impl;

import com.example.werewolf.common.GameStatus;
import com.example.werewolf.model.sse.GameSession;
import com.example.werewolf.service.GameService;
import com.example.werewolf.service.PlayerService;
import com.example.werewolf.utils.PrintUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

@Service
@RequiredArgsConstructor
public class GameServiceImpl implements GameService {
    // 存储用户连接
    private final Map<String, SseEmitter> emitterMap = new ConcurrentHashMap<>();
    // 存储用户会话状态
    private final Map<String, GameSession> sessionMap = new ConcurrentHashMap<>();

    private final PlayerService playerService;

    public SseEmitter connect(String userId) {
        SseEmitter emitter = new SseEmitter(0L); // 永不超时

        emitterMap.put(userId, emitter);
        sessionMap.put(userId, new GameSession(userId, 0, true));

        try {
            emitter.send("连接成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 清理回调
        emitter.onCompletion(() -> {
            emitterMap.remove(userId);
            sessionMap.remove(userId);
        });
        emitter.onTimeout(() -> {
            emitter.complete();
            emitterMap.remove(userId);
            sessionMap.remove(userId);
        });

        return emitter;
    }

    public void nextStage(String userId) {
        GameSession session = sessionMap.get(userId);
        if (session == null || !session.isActive()) {
            throw new RuntimeException("会话不存在或已结束");
        }

        int nextStage = session.getCurrentStage() + 1;
        session.setCurrentStage(nextStage);

        // 推送该阶段的内容（例如 3 条消息）
        SseEmitter emitter = emitterMap.get(userId);
        if (emitter != null) {
            CompletableFuture.runAsync(() -> {
                try {
                    GameStatus gameStatus = playerService.getGameStatus();
                    if (gameStatus.canStartNewGame()) {
                        // 未初始化
                        playerService.initGame("default");
                        PrintUtils.printSystem(emitter, "游戏初始化完成！");
                    } else if (gameStatus.isGaming()){
                        // 下一步
                        playerService.nextStep("roomId", emitter);
                    } else {
                        throw new RuntimeException("游戏状态异常");
                    }
                } catch (IOException e) {
                    emitter.complete();
                    emitterMap.remove(userId);
                    sessionMap.remove(userId);
                }
            });
        }
    }

    public void endGame(String userId) {
        GameSession session = sessionMap.get(userId);
        if (session != null) {
            session.setActive(false);
        }
        SseEmitter emitter = emitterMap.get(userId);
        if (emitter != null) {
            emitter.complete();
            emitterMap.remove(userId);
            sessionMap.remove(userId);
        }
    }
}
